/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.quangtin3.Bouncing;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 * Echo all imcoming data.
 * @author quangtin3@gmai.com
 */
public class EchoServer implements Runnable {

    private int serverPort = 8585;
    private ServerSocket serverSocket;
    Logger log = Logger.getLogger("echoServer");

    public static void main(String[] args) {
        BasicConfigurator.configure();

        new EchoServer();
    }

    public EchoServer() {
        Thread t = new Thread(this, "ECHO");
        t.start();
    }

    public void run() {
        try {
            serverSocket = new ServerSocket(serverPort);
            log.info("Echo server listening on " + serverPort + " ...");
            int count = 0;
            while (true) {
                count++;
                log.info("wait for more connection");
                Socket sock = serverSocket.accept();
                log.info("accept (" + count + ") connection form " +
                        sock.getInetAddress().getHostAddress());

                log.info("create bouncing to echo back");
                new Bouncing(sock, sock, log);
            }
        } catch (Exception e) {
            log.error("echo server error", e);
        }
    }
}
